# encoding: utf-8
# Author    : limusen
# Datetime  : 2023/9/27 09:54
# File      : logs.py
# explain   : 文件说明

import time
import logging
import os
from common.config import local_config

current_path = os.path.dirname(os.path.dirname(__file__))
log_path = os.path.join(current_path, local_config.logs_path)

class FilenameIncludedFormatter(logging.Formatter):
    def format(self, record):
        record.filename = os.path.basename(record.pathname)
        return super().format(record)

class InfoFilter(logging.Filter):
    def filter(self, record):
        return record.levelno == logging.INFO

class ErrorFilter(logging.Filter):
    def filter(self, record):
        return record.levelno == logging.ERROR

class LogUtil:
    def __init__(self, logger_name):
        self.log_name = os.path.join(log_path, f'Test_{time.strftime("%Y_%m_%d")}.log')
        self.error_name = os.path.join(log_path, f'Error_{time.strftime("%Y_%m_%d")}.log')

        self.logger = logging.getLogger(logger_name)
        self.logger.setLevel(logging.DEBUG)  # Set logger level to DEBUG by default

        self._setup_file_handler(self.log_name, logging.INFO, InfoFilter())  # Handle INFO level logs
        self._setup_file_handler(self.error_name, logging.ERROR, ErrorFilter())  # Handle ERROR level logs

        # Add a console handler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)  # You can set the console handler level as needed
        console_handler.setFormatter(FilenameIncludedFormatter('%(asctime)s - %(levelname)s - %(filename)s - %(message)s'))
        self.logger.addHandler(console_handler)

    def _setup_file_handler(self, filename, level, log_filter):
        file_handler = logging.FileHandler(filename, 'a', encoding='utf-8')
        file_handler.setLevel(level)
        formatter = FilenameIncludedFormatter('%(asctime)s - %(levelname)s - %(filename)s - %(message)s')
        file_handler.setFormatter(formatter)
        file_handler.addFilter(log_filter)
        self.logger.addHandler(file_handler)
        file_handler.close()

    def get_logger(self):
        return self.logger

logger = LogUtil(__name__).get_logger()

if __name__ == '__main__':
    logger.info('fine')
    logger.error("sdasd")
